package allen.util;

/**
 * Provides some util class for string.
 * */
public class StringUtil {
	/**
	 * Convert string to a string at least with length. If input string's length
	 * is less than length, add prefix prefix to it.
	 * */
	private static String addMinLengthPrefix(String input, char prefix,
			int length) {

		if (input == null) {
			StringBuilder sb = new StringBuilder();
			while (length-- > 0) {
				sb.append(prefix);
			}
			return sb.toString();
		}

		if (input.length() >= length)
			return input;

		int gap = length - input.length();
		StringBuilder sb = new StringBuilder(length);
		while (gap-- > 0) {
			sb.append(prefix);
		}
		sb.append(input);
		return sb.toString();
	}

	/**
	 * Convert string to a string at least with length. If input string's length
	 * is less than length, add prefix '0' to it.
	 * */
	public static String addToMinLengthPrefix0(String input, int length) {
		return addMinLengthPrefix(input, '0', length);
	}

	/**
	 * Convert string to a string at least with length. If input string's length
	 * is less than length, add prefix ' ' to it.
	 * */
	public static String addToMinLengthPrefixBlank(String input, int length) {
		return addMinLengthPrefix(input, ' ', length);
	}

	/**
	 * Get percentage string of double value. With 2 digits after dot. If value
	 * is NaN, return "NaN".
	 * */
	public static String getPercentageString(double value) {
		if (Double.isNaN(value)) {
			return "" + Double.NaN;
		}
		StringBuilder sb = new StringBuilder();
		sb.append((int) (value * 100));
		sb.append(".");
		int tail = ((int) (value * 10000)) % 100;
		if (tail < 10) {
			sb.append("0");
		}
		sb.append(tail);
		sb.append("%");

		return sb.toString();
	}

	/**
	 * Get double value from percentage string. The valid string is end with "."
	 * + 2 digits + "%". If the input is invalid, return Double.NaN.
	 * */
	public static double parsePercentageString(String s) {
		if (s == null || !s.endsWith("%")) {
			return Double.NaN;
		}
		if (s.equals("" + Double.NaN)) {
			return Double.NaN;
		}
		int index = s.indexOf(".");
		if (index == -1 || index != s.length() - 4) {
			return Double.NaN;
		}
		s = s.substring(0, s.length() - 1);
		return Double.parseDouble(s) / 100.0;
	}

	/**
	 * Check if s is a null or empty string?
	 * */
	public static boolean isEmptyString(String s) {
		return s == null || s.length() == 0;
	}

	/**
	 * Check if s is a not empty string?
	 * */
	public static boolean isNotEmptyString(String s) {
		return !isEmptyString(s);
	}
}
